<template>
    <div class="create__content">
      <el-form :model="postForm" :rules="rules" ref="postForm" class="form">
        <el-col :span="12" :offset="5">
          <el-form-item class="formTop">
            <h2>创建用户资料</h2>
          </el-form-item>

          <el-form-item label="姓名" label-width="80px" prop="name">
            <el-input v-model="postForm.name" placeholder="请输入用户姓名"></el-input>
          </el-form-item>

          <el-form-item label="昵称" label-width="80px" prop="nickName">
            <el-input v-model="postForm.nickName" placeholder="请输入用户昵称"></el-input>
          </el-form-item>

          <el-form-item label="性别" label-width="80px" prop="sex">
            <el-select v-model="postForm.sex" placeholder="请选择" clearable >
                <el-option v-for="sex in sexList" :key="sex.id" :label="sex.sexName" :value="sex.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="生日" label-width="80px" prop="birth">
            <el-date-picker
                v-model="postForm.birth"
                type="date"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="年级" label-width="80px" prop="gradeId">
            <el-select v-model="postForm.gradeId" clearable >
                <el-option v-for="grade in gradeList" :key="grade.id" :label="grade.gradeName" :value="grade.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="班级" label-width="80px" prop="className">
            <el-select v-model="postForm.className" placeholder="请选择" clearable >
                <el-option
                    v-for="item in classList"
                    :key="item"
                    :label="item+'班'"
                    :value="item+'班'">
                </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="所属地区" label-width="80px">
            <el-cascader change-on-select  clearable placeholder="请选择所属地区" expand-trigger="click" :options="areaCascadeOptionss" v-model="areaOption" @change="getSchools($event)" />
            <span style="color:red;">{{msgArea}}</span>
          </el-form-item>

          <el-form-item label="学校" label-width="80px" prop="schoolId">
            <el-select v-model="postForm.schoolId" v-show="isShow==1" clearable >
                <el-option v-for="item in schools" :key="item.id" :label="item.title" :value="item.id"></el-option>
            </el-select>
            <!-- <span style="color:red;">{{msgSchool}}</span> -->
          </el-form-item>

          <el-form-item label="手机号（必填）" label-width="80px">
            <el-input v-model="mobile" placeholder="请输入11位电话号码" maxlength='11'></el-input>
            <span style="color:red;">{{msgMobile}}</span>
          </el-form-item>

          <el-form-item label="密码" label-width="80px">
            <el-input type="password" v-model="password" auto-complete="new-password" placeholder="请输入6-18位密码" maxlength='18' minlength="6"></el-input> 
            <span class="hint">&nbsp;&nbsp;（若不填，初始密码则为手机号）</span>
            <span style="color:red;">{{msgPassword}}</span> 
          </el-form-item>

          <el-form-item class="leftPaddingChange">
            <el-button  type="primary" :disabled='preventSumit' v-loading='preventSumit' size="small" @click="submitForm()">保存</el-button>
            <el-button  size="small" @click="handleClose" plain>取消</el-button>
          </el-form-item>
        </el-col>  
      </el-form>
    </div>
</template>

<script>
import { getGradeList } from '@/api/grade'
import { getAreaCascadeSupply, getArea } from '@/api/academy'
import { getToken } from '@/utils/auth' // 验权
import JSEncrypt from 'jsencrypt/bin/jsencrypt'
import { getHighSchool, addNewUser } from '@/api/user'

export default{

  name: 'add',
  components: {},
  watch: {
    mobile(e){
      if(!(/^1[345789]\d{9}$/).test(e) && e != ''){
        this.msgMobile = '请输入的正确的手机号码'
      }else{
        this.msgMobile = ''
      }
    },
    areaOption(e){
      if(e.length != 3){
        this.isShow = 0
        this.msgArea = '所属地区必须选择到区级'
      }else{
        this.isShow = 1
        this.msgArea = ''
      }
    },
    password(e){
      if(e.indexOf(' ') >= 0){
        this.msgPassword = '不允许使用空格作为密码'
      }else if(e.trim().length != 0 && (e.trim().length < 6 || e.trim().length > 18)){
        this.msgPassword = '请输入6-18位密码'
      }else{
        this.msgPassword = ''
      }
    }
  },
  data(){
    return {
      headers:{},
      areaOption: [],
      areaCascadeOptionss:[],
      preventSumit:false,
      classList: [],
      schools: [],
      mobile: '',
      password: '',
      msgArea:'',
      // msgSchool:'',
      isShow: 0,
      msgMobile:'',
      msgPassword:'',
      loading: false,
      list: [],
      total: null,
      sexList: [
        { id:0, sexName:'未知' },
        { id:1, sexName:'男' },
        { id:2, sexName:'女' }
      ],
      gradeList: [
        { id:1, gradeName:'高一' },
        { id:2, gradeName:'高二' },
        { id:3, gradeName:'高三' }
      ],
      postForm:{
        name: null,
        nickName: null,
        sex: null,
        birth: null,
        className: null,
        gradeId: null,
        schoolId: null,
        areaId: null,
        mobile: null,
        password: null
      },
      params:{
        areaId:null
      },
      rules: {
        mobile:  [{ required: true, message: '请输入手机号', trigger: 'change' }]
      }

    }
  },
  mounted() {
    this.getClassNames()
    this.getAreaCascadeSupply()
    this.headers = { accessToken:getToken() }
  },
  methods:{
    // 获得班级数据
    getClassNames(){
      let i = 1
      const list = []
      for(i; i < 100; i++){
        list.push(i)
      }
      this.classList = list
    },
    // 获得学校数据
    getSchools(val){
      // console.log("val",val)
      if(val.length == 3){
        this.postForm.areaId = val[val.length - 1]
        this.params.areaId = this.postForm.areaId
        if(this.params != null && this.params != '' && this.params != undefined){
          getHighSchool(this.params).then(res => {
            if(res.code == 0){
              this.schools = res.data
              // console.log("schools",this.schools)
            }
          }).catch(err => {})
        }
      }else{
        this.msgArea = '所属地区必须选择到区级'
      }
    },
    // 获得完整的区域级联,但是要删除 区/县/镇
    getAreaCascadeSupply(){
      getAreaCascadeSupply().then(res => {
        if(res.code == 0){
          // res.data.forEach(item => {
          // if(item.children){
          //     item.children.forEach(i =>{
          //     delete i.children
          //     })
          // }
          // });
          this.areaCascadeOptionss = res.data
        }
      }).catch(err => {})
    },
    // 取消
    handleClose(){
      this.$confirm('数据未保存，确认清空内容？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs.postForm.resetFields()
      }).catch(() => {})
    },
    // 保存
    submitForm(){
      this.postForm.mobile = this.mobile
      if(this.password == null || this.password == ''){
        this.password = this.mobile
      }
      this.postForm.password = this.password
      if(this.postForm.mobile.trim().length == 0 || this.postForm.mobile.length == 0){
        this.$message({
          title: '失败',
          message: '手机号为必填项，请输入后再保存',
          type: 'error',
          duration: 2000
        })
        return
      }
      if(this.areaOption.length != 0 && this.postForm.schoolId == null){
        this.$message({
          title: '失败',
          message: '学校与所属地区，要么全填，要么全不填',
          type: 'error',
          duration: 2000
        })
        return
      }
      const params = this.postForm
      addNewUser(params).then(res => {
        if (res.code == 0) {
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
          this.$router.push({ path:'./list' })
        }else{
          this.$message({
            title: '失败',
            message: message,
            type: 'error',
            duration: 2000
          })
        }
      }).catch(() => {})
    }

  }

}

</script>


<style scoped lang="scss">
.create__content {
  width: 988px;
  margin: 0 auto;
}
.form{
  margin-top: 30px;
}
.hint{
  font-size: 12px;
  color: #999999;
}
.formTop{
  width: 300px;
  margin: 0 auto 20px;
}
.updateBtn{
  width: 300px;
  margin: 50px auto 80px;
}
.leftPaddingChange{
    button{
      min-width:100px;
    }
}
</style>